﻿using System;
using System.Threading;

using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using System.IO.Ports;
using GHIElectronics.NETMF.FEZ;

namespace pandaScreen
{
    public class mainProg
    {
        readonly static SerialPort _serialPort = new SerialPort("COM1", 300) { ReadTimeout = 0 };
     
        readonly static OutputPort led = new OutputPort((Cpu.Pin)FEZ_Pin.Digital.LED, false);  
        static string[] recv;                           // Used to parse the message
        static byte[] MessageBuffer = new byte[300];    // Used to build the message
        static byte[] serialBuffer = new byte[300];     // Used to receive the bytes
        static int readcount = 0;               // Tracks the count of bytes being received through the serial interface.
        static int mbFillLevel = 0;             // Running total of the current fill level of our message buffer.
        static int Newcount = 0;                // Tracks the new count of bytes received to update mbFillLevel
        static int iLocation = 0;               // Tracks the location for array insertion in ReadSerial

        static bool HandledKeyPress = true;     //  Value tracked to prevent double presses of buttons on the serial keybpad until the message is handled


        public static void Main()
        {
        
            byte[] yx_data = System.Text.UTF8Encoding.UTF8.GetBytes("Y");
            byte[] qx_data = System.Text.UTF8Encoding.UTF8.GetBytes("Q");

            byte[] yx_data2 = System.Text.UTF8Encoding.UTF8.GetBytes("Message|Y - Pressed");
            byte[] qx_data2 = System.Text.UTF8Encoding.UTF8.GetBytes("Message|Q - Pressed");

            FEZ_Shields.KeypadLCD.Initialize();
            FEZ_Shields.KeypadLCD.TurnBacklightOn();
            FEZ_Shields.KeypadLCD.CursorHome();
            FEZ_Shields.KeypadLCD.Print("Initialized");

            _serialPort.Open();
            _serialPort.Flush();
            while (true)
            {
                switch (FEZ_Shields.KeypadLCD.GetKey())
                {
                    case FEZ_Shields.KeypadLCD.Keys.Left:
                        if (HandledKeyPress)
                        {
                            HandledKeyPress = false;
                            _serialPort.Write(qx_data, 0, qx_data.Length);
                            FEZ_Shields.KeypadLCD.Clear();
                            FEZ_Shields.KeypadLCD.SetCursor(0, 0);
                            FEZ_Shields.KeypadLCD.Print("Pressed Left Q");

                            //Debug.Print("Left 'Q' Pressed:");
                        }
                        break;
                    case FEZ_Shields.KeypadLCD.Keys.Right:
                        if(HandledKeyPress)
                        {
                            HandledKeyPress = false;
                            _serialPort.Write(yx_data, 0, yx_data.Length);
                            FEZ_Shields.KeypadLCD.Clear();
                            FEZ_Shields.KeypadLCD.SetCursor(0, 0);
                            FEZ_Shields.KeypadLCD.Print("Pressed Left Y");
                            //Debug.Print("Right 'Y' Pressed:");
                        }
                        break;
                    case FEZ_Shields.KeypadLCD.Keys.Up:
                        HandledKeyPress = true;
                        mbFillLevel = 0;
                        break;
                    default:
                        break;
                }

                Thread.Sleep(10);
                ReadSerial();
                if (mbFillLevel == 19)
                {
                    //Debug.Print("GotThere");
                    recv = new string(System.Text.UTF8Encoding.UTF8.GetChars(MessageBuffer)).Split('\n')[0].Split('|');
                    if (recv[0] == "Message")
                    {
                        FEZ_Shields.KeypadLCD.Clear();
                        FEZ_Shields.KeypadLCD.SetCursor(1, 1);
                        FEZ_Shields.KeypadLCD.Print(recv[1]);
                        HandledKeyPress = true;
                        mbFillLevel = 0 ;
                    }
                }
                else
                {
                    if (mbFillLevel == 1)
                    {
                        switch (MessageBuffer[0])
                        {
                            case 81:
                                _serialPort.Write(qx_data2, 0, qx_data2.Length);
                                //Debug.Print("Wrote Q Response");
                                led.Write(false);
                                mbFillLevel = 0;
                                break;
                            case 89:
                                _serialPort.Write(yx_data2, 0, yx_data2.Length);
                                //Debug.Print("Wrote Y Response");
                                led.Write(false);
                                mbFillLevel = 0;
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
        }

        static void ReadSerial()
        {

            readcount = 0;
            Newcount = 0;
            iLocation = mbFillLevel;
            readcount = _serialPort.BytesToRead;
            _serialPort.Read(serialBuffer, 0, serialBuffer.Length);
           
            if (readcount > 0)
            {
                Newcount = mbFillLevel + readcount;
                if (readcount >= 1)
                {
                    mbFillLevel = Newcount;
                    Array.Copy(serialBuffer, 0, MessageBuffer, iLocation, readcount);
                    led.Write(true);
                    //Debug.Print("Received a response");
                }
            }
        }

    }
}
